package com.wt.test.proxy;

import org.springframework.aop.framework.ProxyFactory;
import org.springframework.aop.framework.ProxyFactoryBean;
import org.springframework.aop.support.NameMatchMethodPointcutAdvisor;
import org.springframework.aop.target.HotSwappableTargetSource;

/**
 * spring aop HotSwappableTargetSource，可以解决双数据源自动切换的问题
 * 自定义的CustomTargetSource也可以实现数据源自动切换或其他神奇的功能
 * spring揭秘page 193   9.6.1-第三小节
 * @author: wangtao
 * @date:16:31 2019/3/4
 * @email:taow02@jumei.com
 */
public class AopProxyMain {

	public static void main(String[] args) throws Exception {
		baseProxyTest();
		System.out.println("----------------------------------");
		hotSwappableTargetSource();
		System.out.println("----------------------------------");
		customTargetSource();

	}

	public static void baseProxyTest() {
		MockTask target = new MockTask();
		ProxyFactory weaver = new ProxyFactory();
		weaver.setTarget(target);
		NameMatchMethodPointcutAdvisor advisor = new NameMatchMethodPointcutAdvisor();
		advisor.setMappedName("sayHello");
		advisor.setAdvice(new PerformanceMethodInteceptor());
		weaver.addAdvisor(advisor);
		ITask task = (ITask) weaver.getProxy();
		task.sayHello("wt");
	}

	public static void hotSwappableTargetSource() throws Exception {
		MockTask target = new MockTask();
		ProxyFactoryBean weaverBean = new ProxyFactoryBean();
		HotSwappableTargetSource targetSource = new HotSwappableTargetSource(target);
		weaverBean.setTargetSource(targetSource);
		weaverBean.setInterceptorNames(new String[]{"sayHello"});
		ITask task = (ITask) weaverBean.getTargetSource().getTarget();
		task.sayHello("wt");
		//切换目标类，可以解决双数据源自动切换的问题
		targetSource.swap((ITask) str -> System.out.println("new hello swap " + str));
		ITask newTask = (ITask) weaverBean.getTargetSource().getTarget();
		newTask.sayHello("wt");
		//切换目标类，可以解决双数据源自动切换的问题
		targetSource.swap((ITask) str -> System.out.println("another new hello swap " + str));
		ITask newTask2 = (ITask) weaverBean.getTargetSource().getTarget();
		newTask2.sayHello("wt");
	}

	public static void customTargetSource() throws Exception {
		ProxyFactoryBean weaverBean = new ProxyFactoryBean();
		CustomTargetSource targetSource = new CustomTargetSource(
				str -> System.out.println("this is itask1 ---> hello " + str),
				str -> System.out.println("this is itask2 ---> hello " + str));
		weaverBean.setTargetSource(targetSource);
		weaverBean.setInterceptorNames(new String[]{"sayHello"});
		for (int i = 0; i < 4; i++) {
			ITask task = (ITask) weaverBean.getTargetSource().getTarget();
			task.sayHello("wt");
		}
	}

}
